<template>
	<view class="f30">
		<nav-tab cname="fixedtop" ifsize="30" color="#FE9367" xhxjb="linear-gradient(to right, #fe9367, #FE9367)"
			v-model="aIdx" @changeTab="changeTab" :tabs="tabs"></nav-tab>
		<view class="sxmain">
			<view v-show="aIdx == 0" class="">
				<view class="xxtx f-y-c p13 cd00 cf7c">
					<text class="iconfont iconxxtx cf7c mr20 f36"></text>
					<text class="flex-1 f26">请仔细核对标题/规格等是否与价格对应，避免造成损失，如有错误请修改</text>
				</view>
				<mg-cell cname='bt' ht="通用信息" htc='c3 f30 wei' />
				<view class="bf">
					<mg-input cname="p23" t='number' v-model="params.sort" isr='1' ht='排序' htc='f30' :pr='`请输入排序`'
						icn='f30 c3 t-r' />
					<mg-input @tab="toggleTab('mslx')" :value="params.mslx" isr='1' ht='商品分类' htc='f30' pr='请选择'
						icn='f30 c3 t-r' dis='1' arrow="1" ftc='c3'></mg-input>
					<mg-input v-model="params.name" isr='1' ht='商品名称' htc='f30' pr='请输入商品名称' icn='f30 c3 t-r' />
					<mg-ta title='商品简介' th='100' max='50' v-model="params.body"></mg-ta>
					<mg-cell cname="p332" isr='1'>
						<template slot='bd'>
							<view class="c3 f30">商品主图</view>
							<mg-photo :w='uploadArr[0].w' :max='uploadArr[0].max' :mark='uploadArr[0].mark'
								:pkey='uploadArr[0].pkey' :file-list='uploadArr[0].fileList' @change-img='changeImg' />
						</template>>
					</mg-cell>
					<mg-cell cname="p332" isr='1'>
						<template slot='bd'>
							<view class="c3 f30">商品图片</view>
							<mg-photo :w='uploadArr[1].w' :max='uploadArr[1].max' :mark='uploadArr[1].mark'
								:pkey='uploadArr[1].pkey' :file-list='uploadArr[1].fileList' @change-img='changeImg' />
						</template>>
					</mg-cell>
					<mg-cell hw='230' ht="最小购买量" htc='f30' isr='1'>
						<number-box slot='ft' :min="1" :value='params.minNum' :max="120"
							@change="bindChange($event,'minNum')"></number-box>
					</mg-cell>
					<mg-input @tab="toggleTab('spdw')" :value="params.unit" isr='1' ht='商品单位' hw='200' htc='f30'
						pr='请选择' icn='f30 c3 t-r' dis='1' arrow="1" ftc='c3'></mg-input>
				</view>
				<mg-cell cname='bt' ht="规格信息" htc='c3 f30 wei' />
				<view class="bf">
					<view class="hlb" v-if="!(params.spec.length>0)">
						<!-- <view class="p230">外卖</view> -->
						<view class="f-row p30 f28">
							<view class="f-1 f-c-c hlr">
								<view>价格<text class="cf7c f22">(元)</text></view>
								<input type="digit" v-model="params.price" class="mt10 t-c" placeholder="请输入"></input>
							</view>
							<view class="f-1 f-c-c hlr">
								<view>包装费<text class="cf7c f22">(元)</text></view>
								<input type="digit" v-model="params.boxMoney" class="mt10 t-c"
									placeholder="请输入"></input>
							</view>
							<view class="f-1 f-c-c">
								<view>库存<text class="cf7c f22">(件)</text></view>
								<input type="number" v-model="params.stock" class="mt10 t-c" placeholder="请输入"></input>
							</view>
							<view @click="params.fillType=params.fillType==1?2:1" class="f-1 f-c-c">
								<view>次日置满</view>
								<text class="iconfont mt20" :class="params.fillType==1?'icondx':'icondxk'"
									:style="{color:params.fillType==1?fColor:''}"></text>
							</view>
						</view>
					</view>
					<mg-cell ht="售卖规格" htc='f30' isr='1'>
						<view class="f26" slot='bd' v-if="params.spec.length">{{params.spec.length}}个规格</view>
						<view @click="go({url:'fbsp-gg?arr='+JSON.stringify(params.spec)})" slot='ft'
							class="f-y-c cf7c">
							<text class="iconfont iconbj mr10 cf7c f40"></text>
							<text>编辑</text>
						</view>
					</mg-cell>
					<mg-cell ht="售卖属性" htc='f30' isr='1'>
						<view class="f26" slot='bd' v-if="params.attribute.length">{{params.attribute.length}}个属性
						</view>
						<view @click="go({url:'fbsp-sx?arr='+JSON.stringify(params.attribute)})" slot='ft'
							class="f-y-c cf7c">
							<text class="iconfont iconbj mr10 cf7c f40"></text>
							<text>编辑</text>
						</view>
					</mg-cell>
					<mg-cell ht="售卖加料" htc='f30' isr='1'>
						<view class="f26" slot='bd' v-if="params.feeding.length">{{params.feeding.length}}个加料</view>
						<view @click="go({url:'fbsp-jl?arr='+JSON.stringify(params.feeding)})" slot='ft'
							class="f-y-c cf7c">
							<text class="iconfont iconbj mr10 cf7c f40"></text>
							<text>编辑</text>
						</view>
					</mg-cell>
				</view>
				<mg-cell cname='bt' ht="其他信息" htc='c3 f30 wei' />
				<mg-cell cname="p03" ht="特色分类" htc='f30' isr='1'>
					<view slot='bd'>
						<mg-radio :rsname="{padding:'30rpx 0rpx 30rpx 10rpx'}" rcname='f-x-e' v-model="params.specialType" :arr='specialTypes'></mg-radio>
					</view>
				</mg-cell>
				<mg-cell cname="p03" ht="售卖时间" htc='f30' isr='1'>
					<view slot='bd'>
						<mg-radio rcname='f-x-e' v-model="params.salesType" :arr='smsjArr'></mg-radio>
					</view>
				</mg-cell>
				<view v-show="params.salesType==2" class="p03 bf">
					<mg-cell isr='1' ht="选择时间段">
						<view slot='bd' class="f-y-c">
							<view @click="toggleTab('timeStart')" class="f-1 t-c">{{params.validity[0]||'开始日期'}}</view>
							<view>至</view>
							<view @click="toggleTab('timeEnd')" class="f-1 t-c">{{params.validity[1]||'结束日期'}}</view>
						</view>
					</mg-cell>
					<mg-cell cname="p03"  htc='f30' isr='1'>
						<view slot='bd'>
							<mg-checkbox rcname='f-x-e' v-model="params.weekDay" :arr='weekArr'></mg-checkbox>
						</view>
					</mg-cell>
					<mg-cell cname="p03" ht="售卖时间段" htc='f30' isr='1'>
						<view slot='bd'>
							<mg-radio rcname='f-x-e' v-model="params.weekSalesType" :arr='smsjArr2'></mg-radio>
						</view>
					</mg-cell>
					<view v-show="params.weekSalesType==2">
						<block v-for="(v,i) in params.salesTimeStr" :key='i'>
							<mg-cell isr='1'>
								<view slot='bd' class="f-y-c">
									<view @click="toggleTab('time',{v,i,t:1})" class="f-1 t-c">{{v.startTime||'起始时间'}}
									</view>
									<view>至</view>
									<view @click="toggleTab('time',{v,i,t:2})" class="f-1 t-c">{{v.endTime||'结束时间'}}
									</view>
								</view>
								<view @click="scsd(i)" slot='ft' ftc='f24' :style="{color:fColor}">删除</view>
							</mg-cell>
						</block>
						<mg-cell v-show="params.salesTimeStr.length<3" @tab='tjsd' isr='1' ft='+添加时段' :color='fColor'>
						</mg-cell>
					</view>
				</view>
				<mg-input v-model="params.hotsaleType" formt="2" :color="fColor" isr='1' ht='参与热销排行' hw='220'
					htc='c3 f30' />
				<mg-cell cname="p03" ht="单点时不配送" hw='200' htc='f30' isr='1'>
					<view slot='bd'>
						<mg-radio rcname='f-x-e' v-model="params.aloneType" :arr='ddbpsArr'></mg-radio>
					</view>
				</mg-cell>
				<mg-editor title='商品详情' @input='getEditor' :dval='params.details'></mg-editor>
				<view class="mt20 bf">
					<view class="foot-btnc p-r">
						<button @click="save" :disabled="loading" class="foot-btn"
							:style="{background:fColor}">提交</button>
					</view>
				</view>
				<!--  -->
				<w-picker v-if="spdwArr.length" mode="selector" @confirm="onConfirm($event,'spdw')" ref="spdw"
					:selectList="spdwArr">
				</w-picker>
				<!-- 美食类型 -->
				<w-picker v-if="mslxArr.length" mode="linkage" :level="2" @confirm="onConfirm($event,'mslx')" ref="mslx"
					:linkList="mslxArr">
				</w-picker>
				<w-picker mode="date" startYear="2019" :defaultVal="dateDef1" endYear="2100" :current="false"
					@confirm="onConfirm($event,'timeStart')" :disabledAfter="false" ref="timeStart"></w-picker>
				<w-picker mode="date" startYear="2019" :defaultVal="dateDef2" endYear="2100" :current="false"
					@confirm="onConfirm($event,'timeEnd')" :disabledAfter="false" ref="timeEnd"></w-picker>
				<w-picker mode="time" defaultVal="08:00:00" :current="false" :hasSecond="false"
					@confirm="onConfirm($event,'time')" ref="time" step="1"></w-picker>
			</view>
		</view>
		<mg-load v-show="showloading" type="2"></mg-load>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex'
	import navTab from '@/components/common/functionCmp/nav-tab.vue';
	import numberBox from "@/components/form/number-box.vue"
	import steps from '@/components/third/steps.vue'
	import mgCell from '@/components/common/mg-cell.vue'
	import mgInput from '@/components/form/mg-input.vue'
	import mgPhoto from '@/components/form/mg-photo.vue'
	import mgTa from '@/components/form/mg-ta.vue'
	import mgEditor from '@/components/form/mg-editor.vue'
	import mgLabel from '@/components/form/mg-label.vue'
	import mgRadio from '@/components/form/mg-radio.vue'
	import mgCheckbox from "@/components/form/mg-checkbox.vue"
	import mgAgree from '@/components/form/mg-agree.vue'
	import wPicker from "@/components/form/w-picker.vue";
	import utils from '@/common/utils.js'
	import {
		uploadImg
	} from '@/common/wechat-util.js'
	import {
		utilMixins
	} from "@/common/util-mixins.js"
	export default {
		name: 'my-add-info',
		components: {
			navTab,
			numberBox,
			steps,
			mgCell,
			mgInput,
			mgPhoto,
			mgTa,
			mgEditor,
			mgLabel,
			mgRadio,
			mgCheckbox,
			mgAgree,
			wPicker,
		},
		data() {
			return {
				showloading: false,
				aIdx: 0,
				tabs: [{
						name: '基础信息'
					},
					{
						name: '其他信息'
					},
				],
				specialTypes:[
					{
						value:0,
						name:'无'
					},
					{
						value:1,
						name:'新品'
					},
					{
						value:2,
						name:'热卖'
					},
					{
						value:3,
						name:'推荐'
					}
				],
				smsjArr: [{
						value: 1,
						name: '全时段售卖'
					},
					{
						value: 2,
						name: '自定义时间',
					}
				],
				smsjArr2: [{
						value: 1,
						name: '全时段'
					},
					{
						value: 2,
						name: '自定义',
					}
				],
				weekArr: [{
						value: '周一',
						name: '周一'
					},
					{
						value: '周二',
						name: '周二',
					},
					{
						value: '周三',
						name: '周三'
					},
					{
						value: '周四',
						name: '周四'
					},
					{
						value: '周五',
						name: '周五'
					},
					{
						value: '周六',
						name: '周六'
					},
					{
						value: '周日',
						name: '周日'
					},
				],
				ddbpsArr: [{
						value: 1,
						name: '不配送'
					},
					{
						value: 2,
						name: '正常配送',
					}
				],
				loading: false,
				spdwArr: [],
				mslxArr: [],
				uploadArr: [{
					mark: '0',
					pkey: 'icon',
					w: '174rpx',
					max: '1',
					fileList: [],
					uploadList: [],
				}, {
					mark: '1',
					pkey: 'media',
					w: '174rpx',
					max: '6',
					fileList: [],
					uploadList: [],
				}],
				params: {
					id: '',
					sort: '',
					mslx: '',
					typeId: '',
					name: '',
					body: '',
					icon: [],
					media: [],
					minNum: '1',
					unit: '',
					price: '',
					boxMoney: '',
					stock: '',
					fillType: '2',
					spec: [], //规格
					attribute: [], //属性
					feeding: [], //加料
					salesType: '1',
					validity: [],
					weekDay: [], //星期选择
					weekSalesType: '1', //售卖时间段类别
					salesTimeStr: [], //添加时间段
					hotsaleType: '1', //热销排行
					aloneType: '2',
					details: '',
					goodsType: '1',
					specialType:'0',//特色分类
				},
				editorStr: '',
				zdysd: [],
				dateDef1: '',
				dateDef2: '',
			}
		},
		async onLoad(options) {
			this.showloading = true;
			this.getSystem({
				nosetNB: 1,
			})
			this.util.setNT('保存商品')
			this.params.goodsType = options.type || 1
			this.dateDef1 = this.timeToDate(this.dateToTime(), "yyyy-MM-dd")
			this.dateDef2 = this.timeToDate(new Date().getTime() / 1000 + 2592000, "yyyy-MM-dd")
			this.params.validity = [this.dateDef1, this.dateDef2]
			let arr = await this.util.request({
				'url': this.api.spflsj,
				data: {
					type: options.type
				}
			})
			getApp().globalData.spflsj = arr.data
			this.spdwArr = arr.data.unitData.map(v => ({
				label: v.name,
				value: v.id,
			}))
			this.mslxArr = arr.data.categoryData.map(v => ({
				label: v.label,
				value: v.value,
				children: v.children && v.children.length ? v.children.map(v => ({
					label: v.label,
					value: v.value,
				})) : [{
					label: '',
					value: ''
				}]
			}))
			// console.log(this.dateDef1,this.mslxArr)
			if (options.id) {
				let {
					data
				} = await this.util.request({
					'url': this.api.spbjxq,
					data: {
						id: options.id
					},
				})
				this.spbjxq = data
				for (let k in this.params) {
					if (data.detail.hasOwnProperty(k)) {
						this.params[k] = data.detail[k]
					}
				}
				let pObj = this.mslxArr.find(v => v.value == data.detail.typeId[0]),
					sObj = pObj && data.detail.typeId[1] ? pObj.children.find(v => v.value == data.detail.typeId[1]) ||
					'' : ''
				if (pObj && sObj) {
					this.params.mslx = pObj.label + '-' + sObj.label
				} else if (pObj && !sObj) {
					this.params.mslx = pObj.label
				}
				// // console.log(pObj, sObj)
				data.detail.icon && (this.uploadArr[0].fileList = data.detail.icon.split(','))
				this.uploadArr[1].fileList = data.detail.media || []
				// this.params.id = options.id
				this.editorStr = data.detail.details
				if (data.detail.startTime) {
					this.params.validity = [data.detail.startTime, data.detail.endTime];
				}
				if (data.attrData) {
					this.params.attribute = data.attrData.map((v) => ({
						attrName: v.attrName,
						attrStr: v.attrStr
					}))
				}
				if (data.meterData) {
					this.params.feeding = data.meterData.map((v) => ({
						materialName: v.materialName,
						salesPrice: v.SalesPrice,
						salesStock: v.SalesStock,
						fillType: v.fillType == 1 ? 1 : 2
					}));
				}
				if (data.specsData) {
					this.params.spec = data.specsData.map((v) => ({
						specName: v.specsName,
						price: v.SalesPrice,
						stock: v.SalesStock,
						boxMoney: v.boxMoney,
						crossedPrice: v.crossedPrice,
						costPrice: v.costPrice,
						fillType: v.fillType == 1 ? 1 : 2,
						goodCode: v.goodCode,
						id: v.id,
						goodId: v.goodId
					}));
				}
				if (data.hoursData) {
					this.params.salesTimeStr = data.hoursData.map((v) => ({
						startTime: v.startTime,
						endTime: v.endTime
					}));
				}
				// for (let k in this.params) {
				// 	console.log(`%c ${k} `,
				// 		'color: white; background-color: #07c160', this.params[k])
				// }
			}
			this.showloading = false;
		},
		mixins: [utilMixins],
		computed: {},
		methods: {
			bindChange(e, key) {
				this.params[key] = e
			},
			tjsd() {
				this.params.salesTimeStr.push({
					startTime: '',
					endTime: ''
				})
			},
			scsd(i) {
				console.log(i, this.params.salesTimeStr)
				this.$delete(this.params.salesTimeStr, i)
			},
			changeTab(e) {
				if (e == 1) {
					this.go({
						url: 'fbsp-qtxx?params=' + encodeURIComponent(JSON.stringify({
							id: this.params.id,
							isMember: 2,
							maxNum: this.spbjxq ? this.spbjxq.detail.maxNum : '', //每单限购
							virtualSales: this.spbjxq ? this.spbjxq.detail.virtualSales : '', //虚拟销量
							goodLabel: this.spbjxq ? this.spbjxq.detail.goodLabel || '' : '', //商品标签
							printLabel: this.spbjxq ? this.spbjxq.detail.printLabel || '' : '' //打印标签
						}))
					})
					setTimeout(() => {
						this.aIdx = 0
					}, 200)
				}
				// console.log(e)
			},
			getEditor(e) {
				this.editorStr = e
			},
			async getErStr() {
				let e = this.editorStr
				if (e.indexOf('<img') > -1) {
					let arr = utils.getEditorImgs(e),
						str = e
					let parr = await uploadImg({
						files: arr
					})
					for (let i in arr) {
						str = str.replace(arr[i].imgsrcStr, arr[i].tmp ? parr[i] : parr[i])
					}
					return str.replace(/data-local(\S*)\s/g, "")
				} else {
					return e
				}
			},
			changeImg(e) {
				this.uploadArr[e.mark].uploadList = this.params[e.pkey] = e.p
			},
			toggleTab(str, v) {
				console.log(str, v)
				if (str == 'time') {
					this.selectElement = v
				}
				this.$refs[str].show();
			},
			onConfirm(e, key) {
				console.log(e, key);
				switch (key) {
					case 'timeStart':
						this.$set(this.params.validity, 0, e.result)
						break
					case 'timeEnd':
						this.$set(this.params.validity, 1, e.result)
						break
					case "time":
						this.$set(this.params.salesTimeStr[this.selectElement.i], this.selectElement.t == 1 ? 'startTime' : 'endTime', e.result)
						break
					case "spdw":
						this.params.unit = e.result
						break;
					case "mslx":
						this.params[key] = `${e.checkArr[0]}${e.checkArr[1]?'-'+e.checkArr[1]:''}`
						this.params.typeId = e.checkValue.filter(v => v)
						break;
				}
				console.log(this.params.salesTimeStr)
			},
			async save() {
				let arr = []
				if (this.params.spec.length) {
					arr = ['price', 'boxMoney', 'stock', ]
				}
				let filterArr = ['id', 'media', 'fillType', 'spec', 'attribute', 'feeding', 'weekDay', 'salesTimeStr',
						'body', 'details'
					]
					.concat(arr)
				let judgeData = utils.isFailParams({
					field: this.params,
					filter: filterArr,
					tips: {
						sort: '请输入排序',
						mslx: '请选择分类',
						typeId: '',
						name: '请输入名称',
						body: '',
						icon: '请上传商品主图',
						minNum: '',
						unit: '请选择单位',
						price: '请输入价格',
						boxMoney: '请输入包装费',
						stock: '请输入库存',
						spec: [], //规格
						attribute: [], //属性
						feeding: [], //加料
						salesType: '2',
						validity: [],
						weekDay: [], //星期选择
						weekSalesType: '2', //售卖时间段类别
						salesTimeStr: [], //添加时间段
						hotsaleType: '1', //热销排行
						aloneType: '1',
						details: ''
					}
				})
				if (!judgeData) {
					return
				} else {
					this.showloading = true;
					this.loading = true
					let params = utils.deepCopy(this.params)
					this.util.showLoading('图片上传中')
					let details = await this.getErStr()
					params.details = details
					Promise.all(this.uploadArr.map(item => {
						return uploadImg({
							files: item.uploadList
						})
					})).then(async fres => {
						console.log('parr:',fres)
						params.icon = fres[0].toString()
						params.media = fres[1]
						// for (let k in params) {
						// 	console.log(`%c ${k} `,
						// 		'color: white; background-color: #07c160', params[k])
						// }
						// return
						// console.log(fres, params)
						let res = await this.util.request({
							'url': this.api.spbc,
							ct: 1,
							method: 'POST',
							data: params,
						}).catch(() => {
							this.showloading = false;
						})
						if (!res) {
							this.loading = false
							this.showloading = false;
						} else {
							this.showloading = false;
							this.util.message('保存成功', 1, 1000)
							utils.swnb(1000)
						}
					}).catch(() => {
						this.showloading = false;
					})
				}
			},
		},
	}
</script>

<style scoped lang="scss">
	.sxmain {
		padding-top: 96rpx;
	}

	.xxtx {
		background: #FEF9F0;
	}
</style>
